<template>
  <div class="cate">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- <Breadcrumb /> -->

    <el-card>
      <el-row class="addbtn">
        <el-col>
          <el-button type="primary" @click="showAddCates">添加分类</el-button>
        </el-col>
      </el-row>

      <tree-table
        class="tree-t"
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
      >
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: lightgreen"
          ></i>
          <i class="el-icon-error" style="color: red" v-else></i>
        </template>
        <template slot="sort" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag
            size="mini"
            type="success"
            v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag size="mini" type="warning" v-else>三级</el-tag>
        </template>
        <template slot="handle" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="showeditCate(scope.row.cat_id)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteCate(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加分类 -->
    <el-dialog title="添加分类"  @close="closeCate" :visible.sync="showAddCate" width="40%">
      <el-form
        :model="addCateForm"
        :rules="addCaterules"
        ref="addCateFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>

        <el-form-item label="父级分类">
          <!-- props 用来指定配置对象 -->
          <el-cascader
            v-model="selectKey"
            expandTrigger="hover"
            :options="parentList"
            :props="casProps"
            clearable
            @change="parentChange"
          ></el-cascader>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="showAddCate = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑分类 -->
    <el-dialog title="编辑分类"   :visible.sync="showEditCates" width="40%">
      <el-form
        :model="editCateForm"
        :rules="editCaterules"
        ref="editCateFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showEditCates = false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import Breadcrumb from "../breadcrumb.vue";
export default {
  created() {
    this.getCateList();
  },
  components:{
    Breadcrumb
  },
  data() {
    return {
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      cateList: [],
      total: 0,
      showAddCate: false,
      // 为table指定列的定义
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          type: "template",
          template: "isok",
        },
        {
          label: "排序",
          type: "template",
          template: "sort",
        },
        {
          label: "操作",
          type: "template",
          template: "handle",
        },
      ],
      addCateForm: {
        cat_name: "",
        cat_pid: 0,
        cat_level: 0,
      },
      addCaterules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      parentList: [],
      casProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      selectKey: [],
      showEditCates:false,
      editCateForm:{},
      editCaterules:{
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ]
      }
    };
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) return this.$message.error("获取商品信息失败!");
      this.cateList = res.data.result;
      this.total = res.data.total;
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getCateList();
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getCateList();
    },
    showAddCates() {
      this.getParentList();
      this.showAddCate = true;
    },
    closeCate(){
        this.$refs.addCateFormRef.resetFields()
        this.selectKey = []
        this.addCateForm.cat_level = 0
        this.addCateForm.cat_pid = 0
        
    },
    async getParentList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 },
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取分类信息失败!");
      this.parentList = res.data;
    },
     parentChange() {
            //   console.log(this.selectKey);
      // 如果selectKey数组的length大于0， 证明选中的父级分类
      // 反之，就是没有选中任何父级分类
      if (this.selectKey.length > 0) {
        this.addCateForm.cat_pid = this.selectKey[this.selectKey.length - 1];
        // 为当前的分类的等级赋值
        this.addCateForm.cat_level = this.selectKey.length;
        return;
      } else {
        this.addCateForm.cat_pid = 0;
        // 为当前的分类的等级赋值
        this.addCateForm.cat_level = 0;
      }
    },
     addCate() {
        // console.log(this.addCateForm);
        this.$refs.addCateFormRef.validate(async valid => {
            if(!valid) return 
            const { data: res } = await this.$http.post("categories", this.addCateForm);
            if (res.meta.status !== 201) return this.$message.error("添加分类失败!");
            this.$message.success("添加分类成功!");
            this.showAddCate = false
            this.getCateList()
        })

    },    
    async deleteCate(id) {
        const confirms = await this.$confirm(
            "此操作将永久删除该分类, 是否继续?",
            "提示",
            {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            }
        ).catch((err) => err);
        if (confirms !== "confirm") { return this.$message.info("已取消删除") }
        const { data: res } = await this.$http.delete("categories/" + id);
        if (res.meta.status !== 200) return this.$message.error("删除信息失败！");
        this.$message.success("删除成功！");
        this.getCateList();
    },
    async showeditCate(id) {
        const { data: res } = await this.$http.get("categories/" + id);
        if (res.meta.status !== 200) return this.$message.error("获取分类信息失败");
        this.editCateForm = res.data        
        this.showEditCates = true
    },
    editCate(){
        this.$refs.editCateFormRef.validate(async (valid) => {
            if (!valid) return;
            const { data: res } = await this.$http.put("categories/" + this.editCateForm.cat_id,
                { cat_name: this.editCateForm.cat_name }
            );
            if (res.meta.status !== 200) return this.$message.error("编辑分类信息失败");
            this.$message.success("编辑分类成功");
            this.showEditCates = false;
            this.getCateList();
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.cate {
  .el-card {
    margin: 20px 0;
    .tree-t {
      margin: 20px 0;
    }
  }
  .el-cascader {
    width: 100%;
  }
}
</style>